<template>
  <div class="music-generation-container">
    <!-- 顶部导航 -->
    <div class="top-nav-buttons">
      <div class="nav-btn return-btn" @click="goToHome">
        <span>🏠 返回主页面</span>
      </div>
      <div class="nav-btn results-btn" @click="showResults = !showResults">
        <span>{{ showResults ? '🎵 返回生成' : '📁 查看结果' }}</span>
      </div>
    </div>

    <!-- 顶部介绍 -->
    <div class="header-section">
      <h1 class="main-title">🎵 AI音乐生成器</h1>
      <p class="subtitle">智能AI驱动的音乐创作工具 - 支持中英文输入，一键生成高质量音乐</p>
      <div class="feature-highlights">
        <span class="highlight-tag">🤖 AI智能创作</span>
        <span class="highlight-tag">🌐 中英文支持</span>
        <span class="highlight-tag">⚡ 快速生成</span>
        <span class="highlight-tag">🎼 多种风格</span>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content" v-if="!showResults">
      <!-- 翻译工具卡片 -->
      <div class="tool-card translation-card">
        <h2 class="card-title">
          <span class="icon">🌐</span>
          智能翻译助手
        </h2>
        <p class="card-desc">将中文描述翻译成英文，获得更好的音乐生成效果</p>
        
        <div class="translation-content">
          <div class="input-section">
            <div class="input-group">
              <label>中文描述</label>
              <textarea 
                v-model="translationForm.chineseText" 
                placeholder="请输入中文音乐描述，例如：一首轻快的夏日海滩音乐，有钢琴和吉他伴奏..."
                rows="3"
                @input="onChineseInput"
              ></textarea>
              <div class="char-count">{{ translationForm.chineseText.length }}/500</div>
            </div>
            
            <div class="translate-actions">
              <button 
                class="translate-btn" 
                @click="translateToEnglish"
                :disabled="!translationForm.chineseText.trim() || isTranslating"
              >
                <span v-if="!isTranslating">🔄 翻译成英文</span>
                <span v-else>⏳ 翻译中...</span>
              </button>
              
              <button 
                class="copy-btn" 
                @click="copyTranslatedText"
                v-if="translationForm.englishText"
              >
                📋 复制结果
              </button>
            </div>
          </div>

          <div class="result-section" v-if="translationForm.englishText">
            <div class="input-group">
              <label>英文翻译</label>
              <textarea 
                v-model="translationForm.englishText" 
                readonly
                rows="3"
                placeholder="翻译结果将显示在这里"
              ></textarea>
            </div>
            
            <div class="use-translation">
              <button class="use-btn" @click="useTranslationForMusic">
                🎯 用于音乐生成
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 音乐生成卡片 -->
      <div class="tool-card music-card">
        <h2 class="card-title">
          <span class="icon">🎵</span>
          AI音乐生成
        </h2>
        <p class="card-desc">基于Replicate API的MusicGen模型，生成高质量音乐</p>

        <div class="music-content">
          <!-- 音乐描述输入 -->
          <div class="input-group">
            <label>音乐描述（英文）</label>
            <textarea 
              v-model="musicForm.description" 
              placeholder="Describe the music you want to generate, e.g., upbeat summer beach music with piano and guitar..."
              rows="4"
              @input="onDescriptionInput"
            ></textarea>
            <div class="char-count">{{ musicForm.description.length }}/500</div>
            <div class="language-hint">
              <span class="hint-icon">💡</span>
              <span>建议使用英文描述以获得最佳效果，可通过上方翻译工具转换</span>
            </div>
          </div>

          <!-- 高级参数设置 -->
          <div class="advanced-settings">
            <div class="settings-toggle" @click="showAdvanced = !showAdvanced">
              <span>{{ showAdvanced ? '🔼' : '🔽' }} 高级设置</span>
            </div>
            
            <div class="advanced-content" v-if="showAdvanced">
              <div class="form-row">
                <div class="input-group">
                  <label>音乐时长</label>
                  <select v-model="musicForm.duration">
                    <option value="5">5秒</option>
                    <option value="10">10秒</option>
                    <option value="15">15秒</option>
                    <option value="30">30秒</option>
                    <option value="60">60秒</option>
                  </select>
                </div>

                <div class="input-group">
                  <label>温度值</label>
                  <div class="slider-container">
                    <input 
                      type="range" 
                      v-model="musicForm.temperature" 
                      min="0.1" 
                      max="2.0" 
                      step="0.1"
                      class="slider"
                    >
                    <span class="slider-value">{{ musicForm.temperature }}</span>
                  </div>
                  <div class="slider-desc">值越高，创意性越强</div>
                </div>
              </div>

              <div class="form-row">
                <div class="input-group">
                  <label>模型版本</label>
                  <select v-model="musicForm.modelVersion">
                    <option value="stereo-large">Stereo Large (推荐)</option>
                    <option value="melody">Melody</option>
                    <option value="large">Large</option>
                    <option value="medium">Medium</option>
                  </select>
                </div>

                <div class="input-group">
                  <label>输出格式</label>
                  <select v-model="musicForm.outputFormat">
                    <option value="wav">WAV (高质量)</option>
                    <option value="mp3">MP3 (通用)</option>
                  </select>
                </div>
              </div>
            </div>
          </div>

          <!-- 生成按钮 -->
          <div class="generate-actions">
            <button 
              class="generate-btn" 
              @click="generateMusic"
              :disabled="!musicForm.description.trim() || isGenerating"
            >
              <span v-if="!isGenerating">🎼 生成音乐</span>
              <span v-else>⏳ 生成中...</span>
            </button>
            
            <button 
              class="clear-btn" 
              @click="clearForm"
              type="button"
            >
              🔄 清空表单
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 结果查看区域 -->
    <div class="results-section" v-if="showResults">
      <h2 class="results-title">🎵 生成的音乐文件</h2>
      
      <div v-if="musicFiles.length === 0" class="no-files">
        <div class="empty-state">
          <div class="empty-icon">🎵</div>
          <h3>暂无音乐文件</h3>
          <p>请先在上方生成音乐</p>
        </div>
      </div>
      
      <div v-else class="file-grid">
        <div v-for="file in musicFiles" :key="file.filename" class="file-card">
          <div class="file-icon">🎵</div>
          <div class="file-info">
            <h3 class="file-name">{{ file.filename }}</h3>
            <p class="file-size">{{ formatFileSize(file.size) }}</p>
            <p class="file-time">{{ formatDate(file.created_time) }}</p>
            <p class="file-desc" v-if="file.description">{{ file.description.substring(0, 50) }}...</p>
          </div>
          <div class="file-actions">
            <button @click="previewMusic(file.filename)" class="btn-preview">
              ▶️ 预览
            </button>
            <button @click="downloadMusic(file.filename)" class="btn-download">
              ⬇️ 下载
            </button>
          </div>
        </div>
      </div>
      
      <button @click="refreshFiles" class="btn-refresh">
        🔄 刷新列表
      </button>
    </div>

    <!-- 进度条覆盖层 -->
    <div v-if="processing" class="processing-overlay">
      <div class="processing-content">
        <div class="music-spinner">
          <div class="spinner-wave"></div>
          <div class="spinner-wave"></div>
          <div class="spinner-wave"></div>
          <div class="spinner-wave"></div>
        </div>
        <p class="processing-text">{{ processingMessage }}</p>
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: progress + '%' }"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 状态管理
const showResults = ref(false)
const showAdvanced = ref(false)
const isGenerating = ref(false)
const isTranslating = ref(false)
const processing = ref(false)
const processingMessage = ref('')
const progress = ref(0)

// 表单数据
const translationForm = reactive({
  chineseText: '',
  englishText: '',
  sourceLang: 'zh',
  targetLang: 'en'
})

const musicForm = reactive({
  description: '',
  duration: 10,
  temperature: 1.0,
  modelVersion: 'stereo-large',
  outputFormat: 'wav'
})

const musicFiles = ref([])

// 获取音乐文件列表
const refreshFiles = async () => {
  try {
    const response = await fetch('http://localhost:5000/api/music-generation/results')
    const data = await response.json()
    if (data.success) {
      musicFiles.value = data.files || []
    }
  } catch (err) {
    console.error('获取文件列表失败:', err)
  }
}

// 翻译功能
const translateToEnglish = async () => {
  if (!translationForm.chineseText.trim()) return
  
  isTranslating.value = true
  try {
    const response = await fetch('http://localhost:5000/api/translate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        text: translationForm.chineseText,
        source_lang: 'zh',
        target_lang: 'en'
      })
    })
    
    const data = await response.json()
    
    if (data.success) {
      translationForm.englishText = data.translated_text
    } else {
      alert('翻译失败: ' + data.error)
    }
  } catch (error) {
    alert('翻译请求失败: ' + error.message)
  } finally {
    isTranslating.value = false
  }
}

// 复制翻译结果
const copyTranslatedText = async () => {
  try {
    await navigator.clipboard.writeText(translationForm.englishText)
    alert('已复制到剪贴板')
  } catch (err) {
    alert('复制失败，请手动选择复制')
  }
}

// 使用翻译结果
const useTranslationForMusic = () => {
  if (translationForm.englishText) {
    musicForm.description = translationForm.englishText
  }
}

// 音乐生成功能
const generateMusic = async () => {
  if (!musicForm.description.trim()) {
    alert('请输入音乐描述')
    return
  }

  isGenerating.value = true
  processing.value = true
  processingMessage.value = '正在生成音乐...'
  progress.value = 0

  // 模拟进度条
  const progressInterval = setInterval(() => {
    if (progress.value < 90) {
      progress.value += 5
    }
  }, 500)

  try {
    const response = await fetch('http://localhost:5000/api/music-generation', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        descriptions: [musicForm.description],
        duration: musicForm.duration,
        temperature: musicForm.temperature,
        model_version: musicForm.modelVersion,
        output_format: musicForm.outputFormat
      })
    })
    
    const data = await response.json()
    
    clearInterval(progressInterval)
    progress.value = 100
    
    if (data.success) {
      alert('音乐生成成功！')
      refreshFiles()
      showResults.value = true
    } else {
      alert('音乐生成失败: '+ data.error)
    }
  } catch (error) {
    alert('请求失败: '+ error.message)
  } finally {
    isGenerating.value = false
    processing.value = false
    clearInterval(progressInterval)
  }
}

// 音乐预览和下载
const previewMusic = (filename) => {
  window.open(`http://localhost:5000/api/music-generation/preview/${filename}`, '_blank')
}

const downloadMusic = (filename) => {
  window.open(`http://localhost:5000/api/music-generation/download/${filename}`, '_blank')
}

// 工具函数
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDate = (timestamp) => {
  const date = new Date(timestamp * 1000)
  return date.toLocaleString('zh-CN')
}

const clearForm = () => {
  musicForm.description = ''
  musicForm.duration = 10
  musicForm.temperature = 1.0
  translationForm.chineseText = ''
  translationForm.englishText = ''
}

// 输入监听
const onChineseInput = () => {
  if (translationForm.chineseText.length > 500) {
    translationForm.chineseText = translationForm.chineseText.substring(0, 500)
  }
}

const onDescriptionInput = () => {
  if (musicForm.description.length > 500) {
    musicForm.description = musicForm.description.substring(0, 500)
  }
}

// 监听结果页面变化
watch(showResults, (newVal) => {
  if (newVal) {
    refreshFiles()
  }
})

// 返回首页
const goToHome = () => {
  router.push('/')
}

// 页面加载时获取参数信息
onMounted(() => {
  refreshFiles()
})
</script>

<style scoped>
@import '../assets/MusicGeneration.css'
</style>
